package com.huangdada.hfweather.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**  
* 类说明   
*  
* @author kangy 
* @date 2016年8月8日  新建  
*/
public abstract class HttpClientUtils {

	private static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class);
	
    public static CloseableHttpClient getDefaultHttpClient() {
        return HttpClients.createDefault();
    }
    
	public static CloseableHttpClient createSSLClientDefault() throws Exception {

		SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
				null, new TrustStrategy() {
					// 信任所有
					public boolean isTrusted(X509Certificate[] chain,
							String authType) throws CertificateException {
						return true;
					}
				}).build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				sslContext);
		return HttpClients.custom().setSSLSocketFactory(sslsf).build();

	}
	
	public static CloseableHttpClient createSSLClientNeedJkc3() {
		try {
			
			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            FileInputStream trustStoreInput = new FileInputStream(new File("D:\\work\\ltf\\ssl\\server.j-tour.cn.truststore"));
            trustStore.load(trustStoreInput, "jtour123".toCharArray());
 
			SSLContext sslcontext = new SSLContextBuilder()
					.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
                    .build();
            
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
			return HttpClients.custom()
			        .setSSLSocketFactory(sslsf)
			        .build();
			
		}  catch (Exception e) {
			e.printStackTrace();
		}
        return HttpClients.createDefault();

    }
	
	public static String get (String url){
		return get(url, null);
	}
	
	public static String get (String url, Map<String, String> mapHeaders){
		String result = "";
		CloseableHttpClient httpclient = null;
        try {
        	if(url.startsWith("https")){
        		httpclient = createSSLClientDefault();
        	}else{
        		httpclient = getDefaultHttpClient();
        	}
            // 构造请求URL内容
            log.debug("URL:" + url);
            
            // 创建HttpGet
            HttpGet httpget = new HttpGet(url);

            if(mapHeaders != null && mapHeaders.size()>0){
	            for (Entry<String, String> entry: mapHeaders.entrySet()) {  
	                httpget.setHeader(entry.getKey(), entry.getValue());
	            }
            }else{
                httpget.setHeader("Accept", "application/json");
                httpget.setHeader("Content-Type", "application/json;charset=utf-8");
            }
            
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();//设置请求和传输超时时间
            httpget.setConfig(requestConfig);
            
            // 执行客户端请求
            CloseableHttpResponse response = httpclient.execute(httpget);
            
            try{
	            // 获取响应实体信息
	            HttpEntity entity = response.getEntity();
	            if (entity != null) {
	                result = EntityUtils.toString(entity, "UTF-8");
	            }
	            // 确保HTTP响应内容全部被读出或者内容流被关闭
	            EntityUtils.consume(entity);
            } finally{
            	response.close();
            }
        } catch (Exception e) {
            throw new RuntimeException("httpclient get request error", e);
        } finally {
            // 关闭连接
            if (httpclient != null) {  
                try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}  
            }
        }
        return result;
	}
	
	public static String post (String url, String body){
		String result = "";
		CloseableHttpClient httpclient = null;
        try {
        	if(url.startsWith("https")){
        		httpclient = createSSLClientDefault();
        	}else{
        		httpclient = getDefaultHttpClient();
        	}
            // 构造请求URL内容
            log.debug("URL:" + url);
            log.debug("body请求体:" + body);
            
            // 创建HttpPost
            HttpPost httppost = new HttpPost(url);
            httppost.setHeader("Accept", "application/json");
            httppost.setHeader("Content-Type", "application/json;charset=utf-8");
            
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//设置请求和传输超时时间
            httppost.setConfig(requestConfig);
            
            BasicHttpEntity requestBody = new BasicHttpEntity();
            requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
            requestBody.setContentLength(body.getBytes("UTF-8").length);
            httppost.setEntity(requestBody);
            // 执行客户端请求
            CloseableHttpResponse response = httpclient.execute(httppost);
            
            try{
	            // 获取响应实体信息
	            HttpEntity entity = response.getEntity();
	            if (entity != null) {
	                result = EntityUtils.toString(entity, "UTF-8");
	            }
	            // 确保HTTP响应内容全部被读出或者内容流被关闭
	            EntityUtils.consume(entity);
            } finally{
            	response.close();
            }
        } catch (Exception e) {
        	throw new RuntimeException("httpclient post request error", e);
        } finally {
            // 关闭连接
            if (httpclient != null) {  
                try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}  
            }
        }
        return result;
	}
	
}
